<template>
  <div class="mx-[25px] sm:m-[30px_14px] xl:m-[50px]">
    <div
      v-if="title || viewAllUrl"
      class="flex items-baseline mb-[15px] xl:mb-[20px]"
    >
      <h2 v-if="title" class="text-[18px] xl:text-[24px]">
        {{ title }}
      </h2>

      <router-link
        v-if="viewAllUrl"
        :to="viewAllUrl"
        class="ml-[10px] text-xs text-primary xl:text-sm hover:opacity-80 focus:opacity-80"
      >
        <strong>Explore All</strong>
      </router-link>
    </div>

    <div class="flex  flex-wrap ">
      <Card
        class="w-[calc(100%/3)] p-1 md:w-[calc(100%/4)] md:p-2 lg:w-[calc(100%/5)] xl:w-[calc(100%/6)] 2xl:w-[calc(100%/8)]"
        v-for="item in items.results"
        :key="`card-${item.id}`"
        :item="item"
      />
    </div>

    <div v-if="items.page < items.total_pages" class="py-10 flex items-center w-full justify-center">
       <RiLoaderLine class="fill-primary animate-spin"/>
    </div>
  </div>
</template>
<script setup>
import Card from "./Card.vue";
import { useDebounceFn, useEventListener } from "@vueuse/core";
import { RiLoaderLine } from "vue-icons-plus/ri";
const { title, viewAllUrl, items, show, loading } = defineProps({
  title: {
    type: String,
    required: false,
    default: "",
  },

  viewAllUrl: {
    type: Object,
    required: false,
    default: function () {
      return null;
    },
  },

  items: {
    type: Object,
    required: true,
  },

  show: {
    type: Number,
    required: false,
    default: null,
  },

  loading: {
    type: Boolean,
    required: false,
    default: false,
  },
});

const emit = defineEmits(["loadMore"]);

if (show) {
  items.results = items.results.slice(0, show);
  item.total_pages = 1;
  items.total_results = show;
}

const debouncedFn = useDebounceFn(() => {
  if (items.page < items.total_pages) {
    const bottomOfWindow =
      window.innerHeight + window.pageYOffset >=
      document.body.offsetHeight - 600;
    if (bottomOfWindow && !loading) {
      loadMore();
    }
  } else {
    window.removeEventListener("scroll", debouncedFn);
  }
}, 1000);

useEventListener(window, "scroll", debouncedFn);

const loadMore = () => {
  emit("loadMore");
};
</script>
